package butines.common.graph;

import java.util.ArrayList;
import java.util.Iterator;

public class Edges implements Iterable<Edge> {
	
	private int id;
	private Node owner;
	private ArrayList<Edge> list;
	
	public Edges(Node node) {
		owner = node;
		id = owner.getId();
		list = new ArrayList<Edge>();
	}
	
	public void add(Edge edge) {
		if (edge == null) {
			throw new IllegalArgumentException("Argument 'edge' is null");
		}
		if (edge.getFrom().getId() != id) {
			throw new IllegalArgumentException("Argument 'edge from' is invalid");
		}
		if (exists(edge.getTo())) {
			throw new IllegalArgumentException("Already exists edge to node");
		}
		list.add(edge);
	}
	
	public void remove(Edge edge) {
		if (edge == null) {
			throw new IllegalArgumentException("Argument 'edge' is null");
		}
		if (list.contains(edge) == false) {
			throw new IllegalArgumentException("Edge not found");	
		}
		list.remove(edge);
	}
	
	public void remove(Node to) {
		if (to == null) {
			throw new IllegalArgumentException("Argument 'to' is null");
		}
		Edge edge = get(to);
		if (edge != null) {
			list.remove(edge);
		}
	}
	
	public void removeAll() {
		list.clear();
	}

	public void reverseRemove(Node to) {
		to.getEdges().remove(owner);
	}
	
	public void reverseRemoveAll() {
		for (Edge edge: this) {
			Node to = edge.getTo();
			to.getEdges().remove(owner);
		}
	}
	
	public void destory() {
		reverseRemoveAll();
		removeAll();
	}
	
	public boolean exists(int to) {
		for (Edge edge: this) {
			if (edge.getTo().getId() == to) {
				return true;
			}
		}
		return false;
	}
	
	public Edge get(int to) {
		for (Edge edge: this) {
			if (edge.getTo().getId() == to) {
				return edge;
			}
		}
		return null;
	}
	
	public Edge get(Node to) {
		return get(to.getId());
	}
	
	public boolean exists(Node to) {
		return exists(to.getId());
	}
	
	public int count() {
		return list.size();
	}
	
	// implements Iterable
	public Iterator<Edge> iterator() {
		return list.iterator();
	}

}
